package playground.fs.andnnl;

import playground.fs.LogFileScanner;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by andnnl on 2020/3/10.
 */
public class LogScannerJava8 implements LogFileScanner {

    @Override
    public List<String> doScan(File logFileDir, String keyword) throws Exception {
        Path path = Paths.get(logFileDir.getAbsolutePath());
        Stream<Path> files = Files.list(path).filter(f -> f.getFileName().toString().endsWith("log"));
        Map<String, Long> rsMap = new HashMap<>();
        files.parallel().forEach(p -> {
            try {
                Map<String, Long> map = Files.lines(p).filter(s -> s.contains(keyword))
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
                map.forEach((k, v) -> rsMap.merge(k, v, Long::sum));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        //仅排序Long
//        List<String> rs=rsMap.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed())
//                .map(a -> a.getValue() + " " + a.getKey())
//                .collect(Collectors.toList());
        //先排序Long，再排String
        List<String> rs = rsMap.entrySet().stream().sorted(
                Comparator.comparing(Map.Entry<String, Long>::getValue)
                        .thenComparing(Map.Entry<String, Long>::getKey).reversed())
                .map(a -> a.getValue() + " " + a.getKey())
                .collect(Collectors.toList());

//        rs.forEach(out::println);
        return rs;
    }
}
